<template>
  <s-layout :title="state.isEdit ? '编辑销售订单' : '新增销售订单'">
    <uni-forms
      ref="orderFormRef"
      v-model="state.model"
      :rules="rules"
      validateTrigger="bind"
      labelWidth="160"
      labelAlign="left"
      border
      :labelStyle="{ fontWeight: 'bold' }"
    >
      <view class="bg-white form-box ss-p-x-30">
        <!-- 订单号 -->
        <uni-forms-item name="orderNumber" label="订单号" class="form-item">
          <uni-easyinput
            v-model="state.model.orderNumber"
            placeholder="请输入订单号"
            readonly
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
          />
        </uni-forms-item>

        <!-- 订单时间 -->
        <uni-forms-item name="orderTime" label="时间" class="form-item">
          <uni-datetime-picker type="date" v-model="state.model.orderTime" :clear-icon="false" placeholder="请选择订单时间" />
        </uni-forms-item>

        <!-- 客户名称 -->
        <uni-forms-item name="customerName" label="客户" class="form-item">
          <picker mode="selector" :range="state.customerNames" @change="onCustomerChange" :value="state.customerIndex">
            <uni-easyinput
              disabled
              v-model="state.customerNames[state.customerIndex]"
              placeholder="请选择客户"
              :inputBorder="false"
              placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            />
          </picker>
        </uni-forms-item>

        <!-- 产品清单 -->
        <view class="product-list-header">
          <view>产品清单</view>
          <button type="primary" @click="addProduct" class="add-product-button">+添加产品</button>
        </view>
        <view class="product-list">
          <view v-for="(product, index) in state.model.orderProducts" :key="index" class="product-item">
            <uni-forms-item :name="'product.' + index + '.name'" label="产品" class="form-item">
              <picker mode="selector" :range="state.productNames" @change="onProductChange(index, $event)" :value="product.productIndex">
                <uni-easyinput
                  disabled
                  v-model="state.productNames[product.productIndex]"
                  placeholder="请选择产品"
                  :inputBorder="false"
                  placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
                />
              </picker>
            </uni-forms-item>
            <!-- 其他产品信息... -->
            <uni-forms-item :name="'product.' + index + '.count'" label="数量" class="form-item">
              <uni-easyinput
                v-model.number="product.count"
                type="digit"
                placeholder="请输入数量"
                :inputBorder="false"
                placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
                @input="calculateAmount(index)"
              />
            </uni-forms-item>
            <uni-forms-item :name="'product.' + index + '.productPrice'" label="单价" class="form-item">
              <uni-easyinput
                v-model.number="product.productPrice"
                type="digit"
                placeholder="请输入单价"
                :inputBorder="false"
                placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
                @input="calculateAmount(index)"
              />
            </uni-forms-item>
            <uni-forms-item :name="'product.' + index + '.amount'" label="金额" class="form-item">
              <uni-easyinput
                v-model="product.amount"
                readonly
                :inputBorder="false"
                placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
              />
            </uni-forms-item>
            <uni-forms-item :name="'product.' + index + '.taxPercent'" label="税率" class="form-item">
              <uni-easyinput
                v-model.number="product.taxPercent"
                type="digit"
                placeholder="请输入税率"
                :inputBorder="false"
                placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
              />
            </uni-forms-item>
            <uni-forms-item :name="'product.' + index + '.remark'" label="备注" class="textarea-item">
              <uni-easyinput
                type="textarea"
                autoHeight
                v-model="product.remark"
                placeholder="请输入备注"
                :inputBorder="false"
                placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
              />
            </uni-forms-item>
            <button type="warn" size="mini" @click="removeProduct(index)" class="delete-button">删除产品</button>
          </view>
        </view>

        <!-- 定金金额 -->
        <uni-forms-item name="depositPrice" label="定金" class="form-item">
          <uni-easyinput
            v-model.number="state.model.depositPrice"
            type="digit"
            placeholder="请输入定金金额"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
          />
        </uni-forms-item>

        <!-- 附件地址 -->
        <uni-forms-item name="fileUrl" label="附件" class="form-item">
          <uni-file-picker ref="filePicker" v-model="state.fileList" file-mediatype="all" mode="grid" @select="filePicker" />
          <view v-if="state.model.fileUrl">已上传文件路径：{{ state.model.fileUrl }}</view>
        </uni-forms-item>

        <!-- 备注 -->
        <uni-forms-item name="remark" label="备注" class="textarea-item">
          <uni-easyinput
            type="textarea"
            autoHeight
            v-model="state.model.remark"
            placeholder="请输入备注"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
          />
        </uni-forms-item>
      </view>
    </uni-forms>

    <su-fixed bottom :opacity="false" bg="" placeholder :noFixed="false" :index="10">
      <view class="footer-box ss-flex-col ss-row-between ss-p-20">
        <view class="ss-m-b-20">
          <button class="ss-reset-button save-btn ui-Shadow-Main" @tap="submitOrder">保存</button>
        </view>
        <button v-if="state.isEdit" class="ss-reset-button cancel-btn" @tap="onDeleteOrder">删除订单</button>
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import _ from 'lodash-es';
import { getCustomers, getOrderDetails, getProducts,getProductCount, updateSaleOrder,createSaleOrder } from '@/sheep/api/erp/order.js';
import   FileApi  from '@/sheep/api/infra/file.js';

const orderFormRef = ref(null);
const state = reactive({
  isEdit: false,
  model: {
    id: null,
    orderNumber: "",
    orderTime: "",
    customerIndex: -1,
    customerNames: [],
    customers: [],
    saleUserId: null,
    accountId: null,
    discountPercent: 0,
    depositPrice: 0,
    fileList: [],
    fileUrl: "",
    remark: "",
    orderProducts: [],
    productNames: [],
    products: [],
    isSubmitting: false,
  },
  rules: {},
});

// 加载订单详情
const loadOrderDetails = async (orderId) => {
  try {
    const res = await  getOrderDetails(orderId);
    Object.assign(state.model, res.data); // 将获取的数据赋值给state.model
  } catch (error) {
    console.error("获取订单详情失败", error);
  }
};

// 加载客户列表
const fetchCustomers = async () => {
  try {
    const res = await  getCustomers();
    state.customers = res.data;
    state.customerNames = res.data.map(customer => customer.name);
  } catch (error) {
    showToast("获取客户数据失败");
  }
};

// 加载产品列表
const fetchProducts = async () => {
  try {
    const res = await  getProducts();
    state.products = res.data;
    state.productNames = res.data.map(product => product.name);
  } catch (error) {
    showToast("获取产品数据失败");
  }
};

// 文件选择器处理函数
const filePicker = async (file) => {
  if (!file || !file.tempFilePaths.length) {
    showToast("请选择文件");
    return;
  }
  const dataFile = { file: file.tempFiles[0].file, path: file.tempFilePaths[0] };
  try {
    const res = await FileApi.uploadFile(dataFile); // 调用上传接口
    state.model.fileUrl = res.data.url; // 设置上传后的文件路径
    showToast("文件上传成功", "success");
  } catch (error) {
    showToast("文件上传失败");
  }
};

// 显示提示框
const showToast = (message, type = "none") => {
  uni.showToast({
    title: message,
    icon: type,
  });
};

// 客户选择改变事件处理器
const onCustomerChange = (e) => {
  state.model.customerIndex = parseInt(e.detail.value, 10);
  if (state.model.customerIndex !== -1) {
    state.saleUserId = state.customers[state.model.customerIndex].saleUserId;
  }
};

// 产品选择改变事件处理器
const onProductChange = async (index, e) => {
  const productIndex = parseInt(e.detail.value, 10);
  const selectedProduct = state.products[productIndex];
  try {
    const res = await  getProductCount({ productId: selectedProduct.id });
    state.$set(state.model.orderProducts, index, {
      ...state.model.orderProducts[index],
      productIndex,
      id: selectedProduct.id,
      name: selectedProduct.name,
      no: selectedProduct.no,
      standard: selectedProduct.standard,
      stock: res.data,
      productPrice: selectedProduct.salePrice,
      remark: selectedProduct.remark,
    });
  } catch (error) {
    showToast("获取库存失败");
  }
};

// 添加产品到订单
const addProduct = () => {
  state.model.orderProducts.push({
    productIndex: -1,
    id: "",
    name: "",
    no: "",
    stock: 0,
    standard: "",
    count: 0,
    productPrice: 0,
    amount: "0.00",
    taxPercent: 0,
    remark: "",
  });
};

// 删除指定索引的产品
const removeProduct = (index) => {
  state.model.orderProducts.splice(index, 1);
};

// 计算产品金额
const calculateAmount = (index) => {
  const product = state.model.orderProducts[index];
  const count = parseFloat(product.count);
  const productPrice = parseFloat(product.productPrice);
  if (!isNaN(count) && !isNaN(productPrice)) {
    product.amount = (count * productPrice).toFixed(2);
  } else {
    product.amount = "0.00";
  }
};

// 提交订单
const submitOrder = async () => {
  if (state.model.isSubmitting) return;
  state.model.isSubmitting = true;

  if (!state.model.orderNumber || state.model.customerIndex === -1 || state.model.orderProducts.length === 0) {
    showToast("请填写完整订单信息");
    state.model.isSubmitting = false;
    return;
  }

  for (let i = 0; i < state.model.orderProducts.length; i++) {
    const product = state.model.orderProducts[i];
    if (product.count <= 0 || product.productPrice <= 0) {
      showToast(`请填写第 ${i + 1} 个产品的数量和单价`);
      state.model.isSubmitting = false;
      return;
    }
  }

  const timestamp = new Date(state.model.orderTime).getTime();
  if (isNaN(timestamp)) {
    showToast("订单时间格式不正确");
    state.model.isSubmitting = false;
    return;
  }

  const updatedOrder = {
    id: state.model.id,
    no: state.model.orderNumber,
    customerId: state.customers[state.model.customerIndex].id,
    orderTime: timestamp,
    items: state.model.orderProducts.map(item => ({
      productId: item.id,
      count: item.count,
      productPrice: item.productPrice,
      taxPercent: item.taxPercent,
      remark: item.remark,
    })),
    depositPrice: state.model.depositPrice,
    fileUrl: state.model.fileUrl,
    remark: state.model.remark,
  };

  try {
    if (state.isEdit) {
      await OrderApi.updateSaleOrder(updatedOrder);
    } else {
      await OrderApi.createSaleOrder(updatedOrder);
    }
    showToast("订单提交成功", "success");
    uni.navigateBack();
  } catch (error) {
    console.log("error", error);
    showToast("订单提交失败");
    state.model.isSubmitting = false;
  }
};

// 删除订单
const onDeleteOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确认删除此订单吗？',
    success: async function (res) {
      if (!res.confirm) return;
      try {
        await OrderApi.deleteSaleOrder(state.model.id);
        showToast("订单删除成功", "success");
        uni.navigateBack();
      } catch (error) {
        console.log("error", error);
        showToast("订单删除失败");
      }
    },
  });
};

onLoad(async (options) => {
  state.isEdit = !!options.orderId;
  if (state.isEdit) {
    state.model.id = options.orderId;
    await loadOrderDetails(state.model.id);
  }
  await fetchCustomers();
  await fetchProducts();
});
</script>

<style scoped>
/* 样式可以基于现有的样式进行调整，以匹配新的UI设计 */
.form-item {
  margin-bottom: 20rpx;
}
.textarea-item {
  margin-bottom: 20rpx;
}
.product-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.add-product-button {
  margin-left: 20rpx;
}
.footer-box {
  background-color: #fff;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
}
.save-btn,
.cancel-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
}
</style>